﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace General
{
    public static class Encriptador
    {
        public static class RijndaelSimple
        {
            #region Desencriptar
            /// <summary>
            /// Método para desencriptar un texto encriptado.
            /// </summary>
            /// <returns>Texto desencriptado</returns>
            public static string Desencriptar(string textoEncriptado)
            {
                return Desencriptar(textoEncriptado, "pass75dc@avz10", "s@lAvz", "MD5",
                  1, "@1B2c3D4e5F6g7H8", 128);
            }
            /// <summary>
            /// Método para desencriptar un texto encriptado (Rijndael)
            /// </summary>
            /// <returns>Texto desencriptado</returns>
            public static string Desencriptar(string textoEncriptado, string passBase,
              string saltValue, string hashAlgorithm, int passwordIterations,
              string initVector, int keySize)
            {
                byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
                byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
                byte[] cipherTextBytes = Convert.FromBase64String(textoEncriptado);
                PasswordDeriveBytes password = new PasswordDeriveBytes(passBase,
                  saltValueBytes, hashAlgorithm, passwordIterations);
                byte[] keyBytes = password.GetBytes(keySize / 8);
                RijndaelManaged symmetricKey = new RijndaelManaged()
                {
                    Mode = CipherMode.CBC
                };
                ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes,
                  initVectorBytes);
                MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
                CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor,
                  CryptoStreamMode.Read);
                byte[] plainTextBytes = new byte[cipherTextBytes.Length];
                int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0,
                  plainTextBytes.Length);
                memoryStream.Close();
                cryptoStream.Close();
                string plainText = Encoding.UTF8.GetString(plainTextBytes, 0,
                  decryptedByteCount);
                return plainText;
            }
            #endregion
        }
    }
}
